"use strict";
var $global = null;
var infoTypeMap = null;
/* Controllers */
app.controller("summaryReportEntController", ['$scope', '$location', '$rootScope', '$routeParams', 'summaryReportEntService', function ($scope, $location, $rootScope, $routeParams, summaryReportEntService) {
    $global =  $scope;
    var vm = $scope.vm = {};
    vm.p = {};
    vm.result = {};

    vm.p.dt = $routeParams.dt;
    vm.p.dt2 = $routeParams.dt2;
    vm.p.topic = $routeParams.topic;
    vm.p.etp = $routeParams.etp;
    vm.p.bu = $routeParams.bu;
    vm.p.info = $routeParams.info;

    vm.p.biz='all';
    vm.p.platform = '0';
    /*
    140	platform,info_etpname
    231	platform,info_etpname,info_buid
    207	platform,info_etpname,info_buid,info_id,info_type
    100	platform,info_etpname,info_buid,info_id,info_type,info_local1,info_cate3,package_type
    **/
    vm.d = {etp:'140',buid:'231',info:'207',cube:'100'};
    vm.p.topicId = vm.d.etp;
    if (vm.p.topic != '0') {
        vm.p.topicId = vm.p.topic;
    }
    if (vm.p.etp != '0') {
        vm.p.infoEtpname = vm.p.etp;
    }
    if (vm.p.bu != '0') {
        vm.p.infoBuid = vm.p.bu;
    }
    if (vm.p.info != '0') {
        vm.p.infoId = vm.p.info;
    }

    var datePicker = $('.date');
    datePicker.datetimepicker({
        locale: 'zh-cn',
        format: 'YYYY-MM-DD'
    });
    datePicker.on('dp.hide', function (e) {
        var currentInput = $(e.currentTarget).find('input');
        var eName = currentInput.attr('name');
        var p = $scope.vm.p;
        p[eName] = currentInput.val();
        $scope.$apply()
    });

    if ($scope.vm.p.dt == '' || $scope.vm.p.dt == '0' || typeof ($scope.vm.p.dt) == 'undefined') {
        $scope.vm.p.dt = new Date(new Date().getTime() - 86400000*2).format('yyyy-MM-dd');
    }
     if ($scope.vm.p.dt2 == '' || $scope.vm.p.dt2 == '0' || typeof ($scope.vm.p.dt2) == 'undefined') {
         $scope.vm.p.dt2 = new Date(new Date().getTime() - 86400000).format('yyyy-MM-dd');
     }

    var errorFn = function (result) {
        alert(result);
    };
    $scope.queryReport = function () {
        $scope.listSummaryReport();
    };

    $scope.listSummaryReport = function () {
        $("#refreshTable").addClass('disabled');
        $("#list_table").bootstrapTable('showLoading')
        var vm = $scope.vm;
        vm.result.ms = "...";

        vm.p.dimension = 'info_etpname';
        if(vm.p.platform!='0') {
            vm.p.dimension = 'platform,info_etpname';
        }
        var params = {
            dt: vm.p.dt,
            dt2: vm.p.dt2,
            topicId: vm.p.topicId,
            dimension: vm.p.dimension,
            biz: vm.p.biz,
            platform: vm.p.platform,
            isNewcate3: vm.p.isNewcate3,
            infoEtpname: vm.p.infoEtpname
        }
        if(vm.p.platform=='0') {
            params.platform = null;
        }
        var procFn = function (response) {
            vm.result.ms = response.ms;
            var data = response.data;
            $('#list_table').bootstrapTable('hideLoading');
            $("#refreshTable").removeClass('disabled');
            if (data == null) return;
            vm.result.data = data;
            $('#list_table').bootstrapTable('load', data);

        };
        summaryReportEntService.listSummaryReport(params, procFn, errorFn);
    };

    $scope.initBuserType = function() {
        var vm = $scope.vm;
        var buserTypes0 = [{'k':'', 'v':'全部'}];
        var buserTypes = buserTypeDefined();
        vm.d.buserTypes = buserTypes0.concat(buserTypes);
        vm.p.buserType = vm.d.buserTypes[0].k;
    };

    $scope.initInfoType = function() {
        var vm = $scope.vm;

        if(infoTypeMap==null) {
            infoTypeMap = {};
        }
        var infoTypes = [
            {'k':'', 'v':'全部'}
        ];
        var params = {};
        var procFn = function (response) {
            var data = response.data;
            if (data == null) {
                alert("请求失败：" + response.message);
                return;
            }
            for(var i=0;i<data.length;++i) {
                var key = data[i].attrValue;
                var val = data[i].attrName;
                infoTypes.push({'k':key,'v':val});
                infoTypeMap[key] = val;
            }
            vm.d.infoTypes = infoTypes;
            vm.p.infoType = vm.d.infoTypes[0].k;
        };
        summaryReportEntService.listAdtypeDefine(params, procFn, errorFn);
    };

    $scope.initInfoLocal1 = function() {
        var vm = $scope.vm;
        var infoLocal1s = [{'k':'', 'v':'全部'}];

        var params = {};
        var procFn = function (response) {
            var data = response.data;
            if (data == null) {
                alert("请求失败：" + response.message);
                return;
            }
            for(var i=0;i<data.length;++i) {
                infoLocal1s.push({'k':data[i].k,'v':data[i].v});
            }
            vm.d.infoLocal1s = infoLocal1s;
            vm.p.infoLocal1 = vm.d.infoLocal1s[0].k;
        };

        summaryReportEntService.listDictCmcDispLocal(params, procFn, errorFn);
    };
    $scope.initInfoCate3 = function() {
        var vm = $scope.vm;
        var infoCate3s = [
            {'k':'', 'v':'全部'}
        ];

        var params = {};
        var procFn = function (response) {
            vm.result = response;
            var data = response.data;
            if (data == null) {
                alert("请求失败：" + response.message);
                return;
            }
            for(var i=0;i<data.length;++i) {
                infoCate3s.push({'k':data[i].k,'v':data[i].v});
            }
            vm.d.infoCate3s = infoCate3s;
            vm.p.infoCate3 = vm.d.infoCate3s[0].k;
        };
        summaryReportEntService.listDictCmcCate3(params, procFn, errorFn);
    };



    $scope.toggleInteval = function (topicId) {
        var vm = $scope.vm;
        vm.p.topicId = topicId;
        //$location.path('/star/report/summary_report/'+ vm.p.dt+'/'+ vm.p.dt2+'/'+ vm.p.topicId + '/0/0/0').replace();
        if (vm.p.topicId == vm.d.etp) {
            $location.path('/star/report/summary_report_ent/'+ vm.p.dt+'/'+ vm.p.dt2+'/'+ vm.p.topicId + '/0/0/0').replace();
        } else if (vm.p.topicId == vm.d.buid) {
            $location.path('/star/report/summary_report_bu/'+ vm.p.dt+'/'+ vm.p.dt2+'/'+ vm.p.topicId + '/0/0/0').replace();
        } else if (vm.p.topicId == vm.d.info) {
            $location.path('/star/report/summary_report_info/'+ vm.p.dt+'/'+ vm.p.dt2+'/'+ vm.p.topicId + '/0/0/0').replace();
        } else if (vm.p.topicId == vm.d.cube) {
            $location.path('/star/report/summary_report_channel/'+ vm.p.dt+'/'+ vm.p.dt2+'/'+ vm.p.topicId + '/0/0/0').replace();
        }

    }

    $scope.toMetricChart = function (field, index) {
        var $table = $('#list_table')
        var tableData = $table.bootstrapTable('getData');

        var dom = document.getElementById('metric_chart');
        var myChart = echarts.init(dom);
        myChart.showLoading()

        var row = tableData[index]
        var params = {
            field: field,
            dimension: row.dimension,
            biz: row.biz,
            platform: row.platform,
            infoEtpname: row.infoEtpname
        };
        var procFn = function (response) {
            vm.result = response;
            var data = response.data;
            if (data == null) {
                alert("请求失败：" + response.message);
                return;
            }
            let modalTitle = '趋势图'

            $scope.vm.modalTitle = modalTitle
            initChart(myChart, data.chartData, field)
            myChart.hideLoading()
        };
        summaryReportEntService.getSummaryReportEntChart(params, procFn, errorFn);

        $('#myModal').modal('show')
    }
    $scope.toMetricChart2 = function (field, index) {
        var $table = $('#list_table')
        var tableData = $table.bootstrapTable('getData');

        var dom = document.getElementById('metric_chart');
        var myChart = echarts.init(dom);
        myChart.showLoading()

        var row = tableData[index]
        var params = {
            field: field,
            dimension: 'ent_name',
            infoEtpname: row.infoEtpname
        };
        var procFn = function (response) {
            vm.result = response;
            var data = response.data;
            if (data == null) {
                alert("请求失败：" + response.message);
                return;
            }
            let modalTitle = '趋势图'

            $scope.vm.modalTitle = modalTitle
            initChart(myChart, data.chartData, field)
            myChart.hideLoading()
        };
        summaryReportEntService.getSummaryReportEntChart2(params, procFn, errorFn);

        $('#myModal').modal('show')
    }

    $scope.hideColumnFunc=function(obj) {
        obj.bootstrapTable('hideColumn', 'topicId');
        obj.bootstrapTable('hideColumn', 'biz');
        obj.bootstrapTable('hideColumn', 'platform');


//        obj.bootstrapTable('hideColumn', 'omsCost');
        // 串联数据隐藏
        obj.bootstrapTable('hideColumn', 'searchCnt1');
        obj.bootstrapTable('hideColumn', 'searchUv1');
        obj.bootstrapTable('hideColumn', 'expCnt1');
        obj.bootstrapTable('hideColumn', 'expUv1');
        obj.bootstrapTable('hideColumn', 'clickCnt1');
        obj.bootstrapTable('hideColumn', 'clickUv1');
        obj.bootstrapTable('hideColumn', 'deliveryCnt1');
        obj.bootstrapTable('hideColumn', 'deliveryUv1');
        obj.bootstrapTable('hideColumn', 'deliveryIdsCnt1');
        obj.bootstrapTable('hideColumn', 'imCnt1');
        obj.bootstrapTable('hideColumn', 'imUv1');
        obj.bootstrapTable('hideColumn', 'imReadCnt1');
        obj.bootstrapTable('hideColumn', 'imReplyCnt1');
        obj.bootstrapTable('hideColumn', 'telCnt1');
        obj.bootstrapTable('hideColumn', 'telUv1');
        obj.bootstrapTable('hideColumn', 'telConnCnt1');
        obj.bootstrapTable('hideColumn', 'telConnUv1');
        obj.bootstrapTable('hideColumn', 'linkUv1');
        obj.bootstrapTable('hideColumn', 'yxCost1');
        obj.bootstrapTable('hideColumn', 'jzCost1');
        obj.bootstrapTable('hideColumn', 'omsCost1');
    }

    $scope.initializeController = function () {
        vm.result.ms = '';
        var $resultTable = $('#list_table');
        $resultTable.bootstrapTable({
            exportDataType: 'all',
            exportTypes: ['excel', 'json', 'xml', 'csv', 'txt'],
            pageList: [30, 50, 100, 300, 500, 1000, 3000], pageSize: 30
        });
        $("#list_table").bootstrapTable('hideColumn', 'searchCnt');
        $("#list_table").bootstrapTable('hideColumn', 'searchUv');
        $("#list_table").bootstrapTable('hideColumn', 'expUv');
        $("#list_table").bootstrapTable('hideColumn', 'clickUv');
        $("#list_table").bootstrapTable('hideColumn', 'deliveryUv');
        $("#list_table").bootstrapTable('hideColumn', 'imUv');
        $("#list_table").bootstrapTable('hideColumn', 'telUv');
        $("#list_table").bootstrapTable('hideColumn', 'jzCost');
        $("#list_table").bootstrapTable('hideColumn', 'yxCost');


        $scope.initBuserType();
        $scope.initInfoType();
        $scope.initInfoLocal1();
        $scope.initInfoCate3();

        $scope.listSummaryReport();
    };

    $scope.initializeController();

}]);

/* Services */
app.service('summaryReportEntService', ['ajaxService', function (ajaxService) {

    this.listSummaryReport = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/report/listSummaryReport.do", successFunction, errorFunction);
    };

    this.getSummaryReportEntChart = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/report/getSummaryReportEntChart.do", successFunction, errorFunction);
    };
    this.getSummaryReportEntChart2 = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/report/getSummaryReportEntChart2.do", successFunction, errorFunction);
    };

    this.listAdtypeDefine = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/adDefine/list.do", successFunction, errorFunction);
    };

    this.listDictCmcDispLocal = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/dict_cmc/listDispLocal1.do", successFunction, errorFunction);
    };
    this.listDictCmcCate3 = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/dict_cmc/listCate3.do", successFunction, errorFunction);
    };

}]);

function initChart(myChart, data, title) {

    var dateList = data.map(function (item) {
        return item[0];
    });
    var valueList = data.map(function (item) {
        return item[1];
    });
    // var dom = document.getElementById("container");

    window.onresize = function () {
        myChart.resize();
    };
    var option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross' }
        },
        legend: {
        },
        dataZoom: [{}],
        xAxis: {
            type: 'category',
            data: dateList
        },
        yAxis: [
            {
                name: '指标值',
                type: 'value'
            }
        ],
        series: [
            {
                name: title,
                yAxisIndex: 0,
                data: valueList,
                type: 'line',
                smooth: true
            }
        ]
    };
    window.onresize = function () {
        myChart.resize();
    };
    if (option && typeof option === 'object') {
        myChart.setOption(option);
    }
}


function summaryReportFormatter(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart('" + field + "'," + index + ")"
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        numberFmt(value),
        '</a>  ',
    ].join('')
}
function summaryReportFormatter2(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart2('" + field + "'," + index + ")"
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        numberFmt(value),
        '</a>  ',
    ].join('')
}

function summaryReportRatioFormatter(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart('" + field + "'," + index + ")"
    var val = numberFmt(value * 100);
    var str = val;
    if (val.indexOf(".") > 0) { // 有小数点
        str = val.substring(0, val.indexOf(".") + 3);
    }
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        str + '%',
        '</a>  ',
    ].join('')
}


function ctrUvFormatter(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart('" + field + "'," + index + ")"
    var val = numberFmt(value * 100);
    var str = val;
    if (val.indexOf(".") > 0) { // 有小数点
        str = val.substring(0, val.indexOf(".") + 3);
    }
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        str + '%',
        '</a>  ',
        '(', row.clickUv1, '/', row.expUv1, ')'
    ].join('')
}
function ctrAsFormatter(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart('" + field + "'," + index + ")"
    var val = numberFmt(value * 100);
    var str = val;
    if (val.indexOf(".") > 0) { // 有小数点
        str = val.substring(0, val.indexOf(".") + 3);
    }
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        str + '%',
        '</a>  ',
        '(', row.clickCnt1, '/', row.expCnt1, ')'
    ].join('')
}

function cvrUvFormatter(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart('" + field + "'," + index + ")"
    var val = numberFmt(value * 100);
    var str = val;
    if (val.indexOf(".") > 0) { // 有小数点
        str = val.substring(0, val.indexOf(".") + 3);
    }
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        str + '%',
        '</a>  ',
        '(', row.linkUv1, '/', row.clickUv1, ')'
    ].join('')
}
function cvrAsFormatter(value, row, index, field) {
    let clickFncStr = "angular.element(this).scope().toMetricChart('" + field + "'," + index + ")"
    var val = numberFmt(value * 100);
    var str = val;
    if (val.indexOf(".") > 0) { // 有小数点
        str = val.substring(0, val.indexOf(".") + 3);
    }
    return [
        '<a href="javascript:void(0)" onclick="' + clickFncStr + '">',
        str + '%',
        '</a>  ',
        '(', row.deliveryCnt1 + '+' + row.imCnt1 + '+' + row.telCnt1, '/', row.clickCnt1, ')'
    ].join('')
}




function platformFormat(value, row, index, field) {
    if (value == 1) {
        return 'pc'
    } else if (value == 2) {
        return 'm'
    } else if (value == 3) {
        return 'app'
    } else if (value == 4) {
        return '小程序'
    } else if (value == 5) {
        return 'wap'
    } else {
        return '-'
    }
}

function infoEtpnameFormat(value, row, index, field) {
    if (value == null) {
        return "-";
    }
    var vm = $global.vm;
    return [
        '<a href="#/star/report/summary_report_bu/', vm.p.dt,'/',vm.p.dt2,'/231/',value, '/0/0" target="_blank"><u>', value, '</u></a>'
    ].join('');
}
function infoBuidFormat(value, row, index, field) {
    if (value == null) {
        return "-";
    }
    var vm = $global.vm;
    return [
        '<a href="#/star/report/summary_report_info/', vm.p.dt,'/',vm.p.dt2,'/207/0/',value, '/0" target="_blank"><u>', value, '</u></a>',
        ' (', row.infoBuname, ')',
    ].join('');
}
function infoIdFormat(value, row, index, field) {
    if (value == null) {
        return "-";
    }
    var vm = $global.vm;
    return [
        '<a href="#/star/report/summary_report_channel/', vm.p.dt,'/',vm.p.dt2,'/100/0/0/',value, '" target="_blank"><u>', value, '</u></a>',
        '（', row.infoName, '）'
    ].join('');
}


function infoLocal1NameFormat(value, row, index, field) {
    if (value == null) {
        return "-";
    }
    return value + '(' + row.infoLocal1 + ')'
}

function infoCate3NameFormat(value, row, index, field) {
    if (value == null) {
        return "-";
    }
    return value + '(' + row.infoCate3 + ')'
}

function isNewcate3Format(value, row, index, field) {
    if (value == 0) {
        return '否'
    } else if (value == 1) {
        return '是'
    } else {
        return '-'
    }
}
var infoTypeMap = null;
var buserTypeMap = null;
function buserTypeFormat(value, row, index, field) {
    if (value == null) {
        return "-";
    }
    if(buserTypeMap ==null ) {
        buserTypeMap = new Map();
        var arr = buserTypeDefined();
        for(var i=0;i<arr.length;++i) {
            var it = arr[i];
            buserTypeMap[it.k] = it.v;
        }
    }
    var val = buserTypeMap[value];
    if (val == null || typeof (val) == 'undefined') {
        return '未知（'+value+')';
    } else {
        return val;
    }
}

function buserTypeDefined() {
    var arr = [
        {'k':'zhizhao','v':'直招'},
        {'k':'daizhao','v':'代招'},
        {'k':'ka','v':'KA客户'},
        {'k':'sanbao','v':'三保'},
        {'k':'baoxian','v':'保险'},
        {'k':'jiaoyu','v':'教育'},
        {'k':'fangchan','v':'房产'},
        {'k':'qishou','v':'骑手'},
        {'k':'wangyueche','v':'网约车'},
        {'k':'官方账号','v':'官方账号'}
    ];
    return arr;
}

function infoTypeFormat(value, row, index, field) {
    if (value == null) {
        return "-";
    }
    if(infoTypeMap==null) {
        return value;
    }
    var val = infoTypeMap[value];
    if (val == null || typeof (val) == 'undefined') {
        return '未知（'+value+')';
    } else {
        return val+'('+value+')';
    }
}

function packageTypeFormat(value, row, index, field) {
    if (value == null || value=='') {
        return "-";
    }
    return value;
}




//function dispLocal1NameFormat(value, row, index, field) {
//    if (value == null) {
//        return "-";
//    }
//    return value + '(' + row.dispLocal1 + ')'
//}

//
//function dispCate2NameFormat(value, row, index, field) {
//    if (value == null) {
//        return "-";
//    }
//    return value + '(' + row.dispCate2 + ')'
//}



